package com.sisqorap.wakeuplight;

import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;

import com.sisqorap.wakeuplight.R;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings.SettingNotFoundException;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.TextView;

public class SnoozeAlarm extends Activity{
	private MediaPlayer MPX;
	private int snoozeTime;
	private Alarm alarm;
	private Timer myTimer;
	
	private static final String SCREEN_BRIGHTNESS_MODE = "screen_brightness_mode";
	private static final int SCREEN_MODE_AUTO = 1;
	private static final int SCREEN_MODE_AUTO_OFF = -1;
	
	private boolean autoBrightOn = false;
	private boolean autoBrightChecked = false;
	
	private TextView tvBrightness;
	
	private NotificationManager nm;
	
	private Calendar check;
	
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
	    setContentView(R.layout.light);
	    ImageButton imgBtn = (ImageButton)findViewById(R.id.btnClose);
	    imgBtn.setOnClickListener(finishAlarm);
	    tvBrightness = (TextView)findViewById(R.id.tvBrightLevel);
	    alarm = new Alarm(SnoozeAlarm.this);
	    Settings setting = new Settings(this);
	    snoozeTime = setting.getSnoozeTime();
	    
	    nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        String tickerText = getString(R.string.set_alarm);
        Notification notif = new Notification(R.drawable.time, tickerText, System.currentTimeMillis());
        Intent intent = this.getIntent();
        //intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
        notif.setLatestEventInfo(this, getString(R.string.app_name), getString(R.string.repeating_received), contentIntent);
        
        notif.ledARGB = 0xFFff0000;
        notif.flags = Notification.FLAG_ONLY_ALERT_ONCE;
        notif.ledOnMS = 100;
        notif.ledOffMS = 100;
        Intent i = new Intent(this,SnoozeAlarm.class);
        PendingIntent pendIntent = PendingIntent.getActivity(this, 0, i, 0);
        notif.setLatestEventInfo(this, "Wake Up Light", "Wake Up Light", pendIntent);
        
        // after a 100ms delay, vibrate for 250ms, pause for 100 ms and
        // then vibrate for 500ms.
        notif.vibrate = new long[] { 100, 250, 100, 500};
        //notif.defaults |= Notification.DEFAULT_SOUND;        
        nm.notify(0, notif);
        
        int minute = alarm.getFirstAlarmMinute();
	    int hour = alarm.getFirstAlarmHour();
	    check = Calendar.getInstance();
	    check.set(Calendar.HOUR_OF_DAY, hour);
	    check.set(Calendar.MINUTE, minute);
	    
	    // Watch for button clicks.
	    /*Button button = (Button)findViewById(R.id.snooze_alarm5);
	    button.setOnClickListener(mStartSnooze5);
	    button.setText((button.getText() + "").replace("[SNOOZETIME]", "+" + snoozeTime));
	    */
	    myTimer = new Timer();
		myTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				Log.v("Timer", "timer runs");
				TimerMethod();
			}
		}, 0, 5*1000);
	}
	
	@Override
	public void onDestroy() {
	    super.onDestroy();
	}
	
	@Override
    public void onNewIntent(final Intent newIntent) 
    {
        super.onNewIntent(newIntent);
    }
	
	private void TimerMethod()
	{
		//This method is called directly by the timer
		//and runs in the same thread as the timer.
		//We call the method that will work with the UI
		//through the runOnUiThread method.
		this.runOnUiThread(Timer_Tick);
	}

	private Runnable Timer_Tick = new Runnable() {
		public void run() {
		//This method runs in the same thread as the UI.    	       
		//Do something to the UI thread here
			Log.v("Timer_Tick", "timer runs");
			OneMinuteTimer();
		}
	};

	
	private void OneMinuteTimer(){
		int percent = 10;
	    Calendar c = Calendar.getInstance();
	    int calcPercent = (int)(((c.getTimeInMillis() - check.getTimeInMillis())/1000f/60f/snoozeTime)*255);
	    Log.v("c", c.getTimeInMillis() + "");
	    Log.v("check", check.getTimeInMillis() + "");
	    Log.v("Percent", calcPercent + "%");
	    if(calcPercent > percent){
	    	percent = calcPercent;
	    }
	    brightness(percent);
	    final Window win = getWindow();
	    win.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD); 
	    win.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

	    if(percent==255){
	    	alarm.removeFirstAlarm();
	    	myTimer.cancel();
		    Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
	        MPX = new MediaPlayer();
	        //Log.i("MediaPlayer", "Created");
	        try{
		        MPX.setDataSource(this, alert);
		        //Log.i("MediaPlayer", "Data Source set");
		        final AudioManager audioManager = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
		        //Log.i("AudioManager", "Audio Manager OK");
		        if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
	                MPX.setAudioStreamType(AudioManager.STREAM_ALARM);
	                MPX.setLooping(true);
	                MPX.prepare();
	                MPX.start();
		        }
	        }catch(Exception ex){
	        	Log.i("Exception", "Exception" );
	        }
	    }
	}
	
	public void brightness(/*float percent*/int brightness){
		ContentResolver cr = getContentResolver();
		int perc = 0;
		float percLp = 0f;
		try{
			autoBrightOn = (android.provider.Settings.System.getInt(cr,SCREEN_BRIGHTNESS_MODE,-1)==SCREEN_MODE_AUTO);
            if(autoBrightOn && !autoBrightChecked)
            {
            	android.provider.Settings.System.putInt(cr, SCREEN_BRIGHTNESS_MODE, SCREEN_MODE_AUTO_OFF);
            }
            autoBrightChecked = true; 
			android.provider.Settings.System.putInt(cr, android.provider.Settings.System.SCREEN_BRIGHTNESS, brightness);
	        WindowManager.LayoutParams lp = getWindow().getAttributes();
	        lp.screenBrightness = brightness / 255.0f;
	        getWindow().setAttributes(lp);
	        perc = android.provider.Settings.System.getInt(cr, android.provider.Settings.System.SCREEN_BRIGHTNESS);
	        percLp = lp.screenBrightness;
		}catch(SettingNotFoundException e){
            Log.d("Bright", "toggleBrightness: " + e);
		}
		tvBrightness.setText(brightness + " - " + perc + " - " + percLp);
		
		/*WindowManager.LayoutParams lp = getWindow().getAttributes();
		float brightness=percent;// we change change brightness strength here
		lp.screenBrightness = brightness;
		getWindow().setAttributes(lp);*/
	}

	private OnClickListener finishAlarm = new OnClickListener() {
        public void onClick(View v) {
        	if(myTimer != null){
        		myTimer.cancel();
        	}
        	if(MPX != null && MPX.isPlaying()){
        		MPX.stop();
        	}
        	alarm.endFirstAlarm();
        	if(autoBrightOn){
        		//Reset auto bright on
        		ContentResolver cr = getContentResolver();
        		try{
        			android.provider.Settings.System.putInt(cr, SCREEN_BRIGHTNESS_MODE, SCREEN_MODE_AUTO);
	    		}catch(Exception e){
	                Log.d("Bright", "toggleBrightness: " + e);
	    		}
        	}
        	nm.cancel(0);
            SnoozeAlarm.this.finish();
        }
    };
}